<?php

namespace App\Service\Cruise\Check;

use App\Library\Rms\RmsShopApi;
use App\Models\Cruise\CruiseCheckAgainstModel;
use App\Models\Cruise\CruiseCheckRectifyModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Models\OpenShop\Common\ShopArchiveModel;
use App\Service\BaseService;
use App\Service\OpenShop\SiteLocation\GuanyuanDataService;
use Illuminate\Support\Facades\Cache;

class CruiseCheckOverviewService extends BaseService
{
    public function overview(): array
    {
        // 待审核单据
        list($countAuditCruiseMission, $countAuditRectify) = $this->waitAuditBills();

        // 商家待处理
        list($countDealRectifyOrder, $countDealRectifyItem, $countWarnAgainst, $countPunishAgainst, $sumAgainst) = $this->waitMerchant();

        // 督导待处理
        list($countDealCheckMission, $countModifyCheckMission) = $this->waitManager();

        // 门店概况
        list($countOnlineShops, $countArchiveMissing) = $this->shop();

        return [
            [
                [
                    'text'     => '待审核单据',
                    'children' => $children = [
                        [
                            'text' => '巡检任务待审核',
                            'num'  => $countAuditCruiseMission,
                        ],
                        [
                            'text' => '整改项待审核',
                            'num'  => $countAuditRectify,
                        ],
                    ],
                    'num'      => array_sum(array_column($children, 'num')),
                ],
                [
                    'text'     => '商家待处理',
                    'children' => $children = [
                        [
                            'text' => '整改单待处理',
                            'num'  => $countDealRectifyOrder,
                            'tips' => "整改项：{$countDealRectifyItem}",
                        ],
                        [
                            'text' => '（警告）违约函',
                            'num'  => $countWarnAgainst,
                        ],
                        [
                            'text' => '（处罚）违约函',
                            'num'  => $countPunishAgainst,
                            'tips' => "违约金额总计：￥{$sumAgainst}元",
                        ],
                    ],
                    'num'      => array_sum(array_column($children, 'num')),
                ],
                [
                    'text'     => '督导待处理',
                    'children' => $children = [
                        [
                            'text' => '巡检任务待处理',
                            'num'  => $countDealCheckMission,
                        ],
                        [
                            'text' => '巡检任务待修改',
                            'num'  => $countModifyCheckMission,
                        ],
                    ],
                    'num'      => array_sum(array_column($children, 'num')),
                ],
            ],
            [
                [
                    'text'     => '门店概况',
                    'children' => [
                        [
                            'text' => '在营门店',
                            'num'  => $countOnlineShops,
                        ],
                        [
                            'text' => '证照异常',
                            'num'  => $countArchiveMissing,
                        ],
                    ],
                ],
            ],
        ];
    }

    /**
     * 待审核单据
     * @return int[]
     */
    private function waitAuditBills(): array
    {
        // 巡检任务待审核
        $countAuditCruiseMission = CruiseOrderModel::query()
                                                   ->where('type', CruiseTemplateModel::TYPE_3)
                                                   ->where('status', CruiseOrderModel::STATUS_NOT_REVIEW)
                                                   ->count();

        // 整改项待审核
        $countAuditRectify = CruiseCheckRectifyModel::query()
                                                    ->where('templateType', CruiseTemplateModel::TYPE_3)
                                                    ->where('status', CruiseCheckRectifyModel::STATUS_WAIT_AUDIT)
                                                    ->count();

        return [$countAuditCruiseMission, $countAuditRectify];
    }

    /**
     * 商家待处理
     * @return array
     */
    private function waitMerchant(): array
    {
        // 整改单待处理
        $countDealRectifyOrder = CruiseCheckRectifyModel::query()
                                                        ->where('templateType', CruiseTemplateModel::TYPE_3)
                                                        ->where('status', CruiseCheckRectifyModel::STATUS_WAIT_SUBMIT)
                                                        ->count();

        // 整改项
        $countDealRectifyItem = $countDealRectifyOrder;

        // 警告函
        $countWarnAgainst = CruiseCheckAgainstModel::query()
                                                   ->where('templateType', CruiseTemplateModel::TYPE_3)
                                                   ->where('status', CruiseCheckAgainstModel::STATUS_WAIT)
                                                   ->where('level', CruiseCheckAgainstModel::LEVEL_WARNING)->count();

        // 处罚函
        $countPunishAgainst = CruiseCheckAgainstModel::query()
                                                     ->where('templateType', CruiseTemplateModel::TYPE_3)
                                                     ->where('status', CruiseCheckAgainstModel::STATUS_WAIT)
                                                     ->where('level', CruiseCheckAgainstModel::LEVEL_PUNISH)->count();

        // 违约金额合计
        $sumAgainst = CruiseCheckAgainstModel::query()
                                             ->where('templateType', CruiseTemplateModel::TYPE_3)
                                             ->where('status', CruiseCheckAgainstModel::STATUS_WAIT)
                                             ->sum('price');
        $sumAgainst = number_format("$sumAgainst", 2, ".", ",");

        return [$countDealRectifyOrder, $countDealRectifyItem, $countWarnAgainst, $countPunishAgainst, $sumAgainst];
    }

    /**
     * 督导待处理
     * @return int[]
     */
    private function waitManager(): array
    {
        // 巡检任务待处理
        $countDealCheckMission = CruiseOrderModel::query()
                                                 ->where('type', CruiseTemplateModel::TYPE_3)
                                                 ->where('status', CruiseOrderModel::STATUS_NOT_SUBMIT)
                                                 ->count();

        // 巡检任务待修改
        $countModifyCheckMission = CruiseOrderModel::query()
                                                   ->where('type', CruiseTemplateModel::TYPE_3)
                                                   ->where('status', CruiseOrderModel::STATUS_NOT_MODIFY)
                                                   ->count();

        return [$countDealCheckMission, $countModifyCheckMission];
    }

    /**
     * 门店概况
     * @return int[]
     */
    private function shop(): array
    {
        // 在营门店
        $onlineShopIds = Cache::remember("CruiseCheckOverviewServiceShop", 1800, function () {
            $shopCodes = collect(GuanyuanDataService::ingShops())->map(function ($item) {
                return (int)$item['门店编码'];
            })->toArray();

            return collect((new RmsShopApi())->getShopByCodes($shopCodes, ['id'])['data']['shopList'])->pluck('id')
                                                                                                      ->toArray();
        });

        // 有营业执照的shopIds
        $archiveShopIds = ShopArchiveModel::query()->where(function ($query) {
            $query->where('businessLicenseEndDate', '>=', date('Y-m-d'))
                  ->orWhere('foodBusinessLicenseEndDate', '>=', date('Y-m-d'));
        })->pluck('shopId')->toArray();

        // 营业执照缺失
        $archiveMissionCount = count(array_diff($onlineShopIds, $archiveShopIds));

        return [count($onlineShopIds), $archiveMissionCount];
    }
}
